package payment.mobilepos.unionpay.com.metroguide.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechError;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import payment.mobilepos.unionpay.com.metroguide.R;
import payment.mobilepos.unionpay.com.metroguide.app.MyApplication;
import payment.mobilepos.unionpay.com.metroguide.bean.StationValue;
import payment.mobilepos.unionpay.com.metroguide.utils.JsonParser;
import payment.mobilepos.unionpay.com.metroguide.utils.SoftKeyboardUtil;
import uk.co.senab.photoview.PhotoView;


public class MainActivity extends BaseActivity<MainPresenter, MainModel> implements MainContract.View, RecognizerListener {
    PhotoView mPhotoView;
    //    AnimatedRecordingView mRecording;
    private List<String> stationValues;
    private String endStationsKey;
    private String startStationKey;
    private TextView mCurrentTv;
    private ImageView mSettingIv;
    private EditText mEt;
    private String currentStation;
    private SharedPreferences mShare;
    private RelativeLayout recodingRl;
    private Button mRecordButton;
    private TextView recordTipsTv;
    private LineWaveVoiceView horvoiceview;
    private TextView replyNameTv;
    private boolean isrecording = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initPermission();
        initPresenter();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
        mPresenter.init();
    }


    @Override
    public void initView() {
        mPhotoView = findViewById(R.id.photo_touch_iv);
        mCurrentTv = findViewById(R.id.main_current_tv);
        mSettingIv = findViewById(R.id.main_setting_iv);

        recodingRl = findViewById(R.id.main_recording_rl);
        mRecordButton = findViewById(R.id.iv_recording);
        recordTipsTv = findViewById(R.id.record_tips);
        horvoiceview = findViewById(R.id.horvoiceview);
        mEt = findViewById(R.id.main_et);
        mShare = MyApplication.getAppContext().getSharedPreferences("share", Activity.MODE_PRIVATE);
        currentStation = mShare.getString("currentStation", "唐镇");
        mCurrentTv.setText(getString(R.string.main_current_station, currentStation));
        loadPhoto();
        mSettingIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setETVisiable(false);
            }
        });

        this.stationValues = Arrays.asList(StationValue.station);
        mEt.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s) && stationValues.contains(s.toString().trim())) {
                    setETVisiable(true);
                    currentStation = s.toString().trim();
                    SoftKeyboardUtil.hideSoftKeyboard(MainActivity.this);
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                    mShare.edit().putString("currentStation", currentStation).commit();
                    mCurrentTv.setText(getString(R.string.main_current_station, s.toString().trim()));

                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mRecordButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isrecording) {
                    isrecording = true;
                    mRecordButton.setSelected(true);

                    horvoiceview.setVisibility(View.VISIBLE);
                    horvoiceview.startRecord();
                    horvoiceview.setText("");
                    mPresenter.getReconizer().startListening(MainActivity.this);
                }
            }
        });
    }

    private void loadPhoto() {
        Glide.with(this)
                .load(R.drawable.shanghaimetro)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .error(R.drawable.ic_empty_picture)
                .thumbnail(0.1f)
                .into(mPhotoView);
    }

    @Override
    public Context getContext() {
        return MainActivity.this;
    }


    @Override
    public void updateView(String price, String path) {
        if ( price != null) {
            Intent intent = new Intent(MainActivity.this, QueryResultActivity.class);
            intent.putExtra("price", price);
            intent.putExtra("path", path);
            this.startActivity(intent);
        }
    }

    public void setETVisiable(boolean isShow) {
        mCurrentTv.setVisibility(isShow ? View.VISIBLE : View.GONE);
        mSettingIv.setVisibility(isShow ? View.VISIBLE : View.GONE);
        mEt.setVisibility(!isShow ? View.VISIBLE : View.GONE);
        mEt.setText("");
        recodingRl.setVisibility(isShow ? View.VISIBLE : View.GONE);
    }


    @Override
    public void onVolumeChanged(int i, byte[] bytes) {

    }

    @Override
    public void onBeginOfSpeech() {

    }

    @Override
    public void onEndOfSpeech() {
        horvoiceview.setVisibility(View.INVISIBLE);
        horvoiceview.stopRecord();
        isrecording = false;
        mRecordButton.setSelected(false);
    }

    // 用HashMap存储听写结果
    private HashMap<String, String> mRecognizerResults = new LinkedHashMap<String, String>();
    private String recognizerResult;

    @Override
    public void onResult(RecognizerResult results, boolean b) {
        String text = JsonParser.parseIatResult(results.getResultString());

        String sn = null;
        // 读取json结果中的sn字段
        try {
            JSONObject resultJson = new JSONObject(results.getResultString());
            sn = resultJson.optString("sn");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mRecognizerResults.put(sn, text);

        StringBuffer resultBuffer = new StringBuffer();
        for (String key : mRecognizerResults.keySet()) {
            resultBuffer.append(mRecognizerResults.get(key));
        }
        recognizerResult = resultBuffer.toString();
        horvoiceview.setText(recognizerResult);
        if (b) {
            if (stationValues.contains(recognizerResult)) {
                Map<String, String> map = JsonParser.getJson(this, false);
                endStationsKey = map.get(recognizerResult);
                startStationKey = map.get(currentStation);
                if (!TextUtils.isEmpty(startStationKey)
                        && !TextUtils.isEmpty(endStationsKey)) {
                    if (startStationKey.equals(endStationsKey)) {
                        Toast.makeText(this, "无法查询！起点站不能为终点站", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    mPresenter.queryFare(startStationKey, endStationsKey);
                    mPresenter.queryPath(startStationKey, endStationsKey);
                    startStationKey = endStationsKey = null;
                }
            } else {
                Toast.makeText(this, "没有相匹配的站点，请重新输入", Toast.LENGTH_SHORT).show();
            }
        }
    }


    @Override
    public void onError(SpeechError speechError) {
        Toast.makeText(this, speechError.getErrorDescription(), Toast.LENGTH_SHORT).show();
        horvoiceview.setVisibility(View.INVISIBLE);
        horvoiceview.stopRecord();
        isrecording = false;
        mRecordButton.setSelected(false);
    }

    @Override
    public void onEvent(int i, int i1, int i2, Bundle bundle) {

    }


    private void initPermission() {


        String permissions[] = {
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.MODIFY_AUDIO_SETTINGS,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_SETTINGS,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.CHANGE_WIFI_STATE,
                Manifest.permission.WRITE_SETTINGS,

        };

        ArrayList<String> toApplyList = new ArrayList<String>();

        for (String perm : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, perm)) {
                toApplyList.add(perm);
                //进入到这里代表没有权限.
            }
        }
        String tmpList[] = new String[toApplyList.size()];
        if (!toApplyList.isEmpty()) {
            ActivityCompat.requestPermissions(this, toApplyList.toArray(tmpList), 123);
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键
            setETVisiable(true);
        } else if (keyCode == KeyEvent.KEYCODE_MENU) {
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_HOME) {
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setETVisiable(true);
    }
}
